package com.uenpay.im.panel.gif;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.qyx.android.weight.view.MyGridView;
import com.uenpay.im.R;

/**
 * @author SL
 * @date 2014/7/12
 * @funcation gifViewpage适配器
 */
public class GifAdapter extends PagerAdapter {
	private static final int ONE_PAGE_COUNT = 8;
	private LayoutInflater _inflater;
	private Context _context;
	private String file_type_name;
	private OnBuildInViewGifSelected _onGifSelected;

	public GifAdapter(Context context, String _file_type_name,
			OnBuildInViewGifSelected onGifSelected) {
		this.file_type_name = _file_type_name;
		_context = context;
		_inflater = LayoutInflater.from(context);
		_onGifSelected = onGifSelected;
	}

	@Override
	public int getCount() {
		return (new ViewGif(file_type_name).size() - 1 + ONE_PAGE_COUNT)
				/ ONE_PAGE_COUNT;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		ViewGif mViewGif = new ViewGif(file_type_name);
		int emoji_size = mViewGif.size();
		ViewPager pViewPager = ((ViewPager) container);
		int maxIndex = Math.min(ONE_PAGE_COUNT * (position + 1), emoji_size);
		ViewGifCover[] grid = new ViewGifCover[maxIndex
				- (ONE_PAGE_COUNT * position)];
		if (emoji_size > position * ONE_PAGE_COUNT) {
			int index = 0;
			for (int i = ONE_PAGE_COUNT * position; i < maxIndex; i++) {
				if (index < grid.length && mViewGif != null) {
					ViewGifCover gifCover = new ViewGifCover();
					gifCover.gifTypeName = file_type_name;
					gifCover.gifName = mViewGif.getGifName(i);
					gifCover.fileHash = mViewGif.getGifFileHash(i);
					gifCover.fileId = mViewGif.getGifFileId(i);
					grid[index] = gifCover;
				}
				index++;
			}
		}

		View view = _inflater.inflate(R.layout.gif_grid, container, false);
		MyGridView gridView = (MyGridView) view
				.findViewById(R.id.yutumei_gridview);
		gridView.setAdapter(new GifGridAdapter(_context, grid));
		pViewPager.addView(view);
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {
				GifGridAdapter adapter = (GifGridAdapter) adapterView
						.getAdapter();
				if (_onGifSelected != null && adapter != null) {
					_onGifSelected.onGifSelected(adapter.getItem(i));
				}
			}
		});
		return view;
	}

	@Override
	public void destroyItem(ViewGroup collection, int position, Object view) {
		((ViewPager) collection).removeView((View) view);
	}
}
